package cn.wolfcode.web.controller;

import cn.wolfcode.domain.*;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmpRoleService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.impl.PermissionServiceImpl;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IEmpRoleService empRoleService;
    @Autowired
    private IPermissionService permissionService;

    @RequiredPermission(name="角色列表",expression="role:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        //key-value
        model.addAttribute("pageInfo",pageInfo);
        return "/role/list";
    }

    @RequiredPermission(name="角色删除",expression="role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        roleService.delete(id);
        return "redirect:/role/list";
    }

    @RequiredPermission(name="员工新增/编辑",expression="role:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        //找所有权限
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);
        if(id!=null){
            //去修改
            //根据角色id找权限
            List<Permission> permissionsForId = roleService.queryPermissions(id);
            model.addAttribute("permissionsForId",permissionsForId);
            Role role = roleService.get(id);
            model.addAttribute("role",role);
        }
        return "/role/input";
    }

    @RequiredPermission(name="员工新增/编辑",expression="role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids){
        if(role.getId()==null){
            //System.out.println(role);
            //执行增加操作
            roleService.insert(role);
        }else{
            //修改之前删除该员工关联角色的关系
            roleService.deleteRelation(role.getId());
            //执行修改操作
            roleService.update(role);
        }
        if(ids!=null){
            for (Long id : ids) {
                roleService.insertRelation(role.getId(),id);
            }
        }
        return "redirect:/role/list";
    }

}
